package com.jiantong.web.controller.version;

import com.jiantong.version.model.VersionControl;
import com.jiantong.version.service.VersionControlReadService;
import com.jiantong.version.service.VersionControlWriteService;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by mz on 9/5/17.
 *
 */
@RestController
@Slf4j
public class VersionController {

    @RpcConsumer
    private VersionControlReadService versionControlReadService;

    @RpcConsumer
    private VersionControlWriteService versionControlWriteService;


    @GetMapping(value = "/api/find/version/by/id")
    public VersionControl findVersionById(@RequestParam Long id){
        if(id == null){
            log.error("this id is not exist");
            throw new OPClientException("id is not exist");
        }
        Response<VersionControl> response = versionControlReadService.findById(id);
        if(!response.isSuccess()){
            log.error("failed to find version by id = {},case = {}",id,response.getError());
            throw new OPServerException(response.getError());
        }
        return response.getResult();
    }

    @GetMapping(value = "/api/query/version/control/list")
    public List<VersionControl> queryList(){
        Response<List<VersionControl>> response = versionControlReadService.queryList();
        if(!response.isSuccess()){
            log.error("failed to query list : case = {} ",response.getError());
            throw new OPServerException(response.getError());
        }
        return response.getResult();
    }

    @PutMapping(value = "/api/update/version/control")
    public Boolean updateVersionControl(@RequestBody VersionControl versionControl){
        if(versionControl.getId() == null){
            log.error("this version control id is null");
            throw new OPClientException("this version control id is null");
        }
        Response<Boolean> response = versionControlWriteService.updateVersionControl(versionControl);
        if(!response.isSuccess()){
            log.error("failed to update version control case = {}",response.getError());
            throw new OPServerException(response.getError());
        }
        return response.getResult();
    }
}
